package com.terren.spider.core.html.scheme.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.terren.spider.entity.core.Entry;

import us.codecraft.webmagic.Page;

public class Auto_Sina_SearchScheme extends BasicCustomScheme{
	
	@Override
	public Set<String> findHelpPaginationUrl(Page page, Entry entry) {
		List<String> pgList = new ArrayList<String>();
		List<String> prevList = page.getHtml().xpath("//a[@class='prev']").links().all();
		if(prevList.size()==2){
			String url1 = prevList.get(0);
			String url2 = prevList.get(1);
			int pageNum1 = Integer.parseInt(StringUtils.substringAfter(url1, "page="));
			int pageNum2 = Integer.parseInt(StringUtils.substringAfter(url2, "page="));
			if(pageNum1>pageNum2){//把下一页放到pgList里面
				pgList.add(url1);
			}else{
				pgList.add(url2);
			}
		//无法判断上一页下一页
		}else if(prevList.size()==1){
			int prevNum = Integer.parseInt(StringUtils.substringAfter(prevList.get(0), "page="));
			int pageOn = Integer.parseInt(page.getHtml().xpath("//a[@class='on']/text()").get());//当前页码
			//如果是下一页
			if(prevNum>pageOn){
				pgList.add(prevList.get(0));
			}	
		}else{//没有上一页下一页
			pgList =page.getHtml().xpath("//div[@class='article_page']").links().all();
		}
		Set<String> resultSet = new HashSet<>();
		resultSet.addAll(pgList);
		return resultSet;
	}
	
	@Override
	public Map<String, String> getCookie(Entry entry) {
		Map<String, String> cookies = new HashMap<>();
		cookies.put("UOR",",db.auto.sina.com.cn,");
		cookies.put("ULV","1528698950278:1:1:1::");
		cookies.put("SINAGLOBAL","23.108.79.105_1528698980.622185");
		cookies.put("Apache","23.108.79.105_1528698980.622188");
		cookies.put("Hm_lvt_f31b3bde5ef6233a36928514fb59f9cd","1528698952");
		cookies.put("Hm_lpvt_f31b3bde5ef6233a36928514fb59f9cd","1528698952");
		return cookies;
	}
}
